package com.guosen.zebra.framework.starter.idm.http.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.guosen.zebra.framework.starter.idm.http.exception.IdmHttpException;
import com.guosen.zebra.framework.starter.idm.http.internal.IdmHttpClient;
import com.guosen.zebra.framework.starter.idm.http.model.request.IdmHttpRequest;
import com.guosen.zebra.framework.starter.idm.http.model.result.IdmHttpRespon;
import com.guosen.zebra.framework.starter.idm.http.properties.IdmHttpProperties;
import com.guosen.zebra.framework.starter.idm.http.service.IdmHttpExecuteService;
import com.guosen.zebra.framework.starter.idm.http.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @className: IdmHttpExecuteServiceImpl
 * @description: idm http接口实现类
 **/
@Slf4j
@Service
public class IdmHttpExecuteServiceImpl implements IdmHttpExecuteService {
    private static final String GET_ACCOUNT_LIST_URL = "/esc-idm/api/v1/ext/account/list";
    private static final String GET_DEPT_LIST_URL = "/esc-idm/api/v1/ext/org/list";
    private IdmHttpProperties idmHttpProperties;

    public IdmHttpExecuteServiceImpl(IdmHttpProperties idmHttpProperties) {
        this.idmHttpProperties = idmHttpProperties;
    }


    @Override
    public IdmHttpRespon getAccountList(IdmHttpRequest request) {
        String url = idmHttpProperties.getUrl() + GET_ACCOUNT_LIST_URL;
        Map<String, String> headers = IdmHttpClient.getHeaders(idmHttpProperties);
        log.info("Get account list   ..., request:{}", request);
        JsonNode jsonResult;
        try {
            jsonResult = IdmHttpClient.post(url, headers, request);
            log.info("Get account list success!");
            return JsonUtil.getObjectMapper().treeToValue(jsonResult, IdmHttpRespon.class);
        } catch (IdmHttpException | JsonProcessingException e) {
            log.error("Get account list failed, request:{},  error message:{}", request, e.getMessage(), e);
            throw new IdmHttpException("查询账号列表错误！", e);
        }
    }

    @Override
    public IdmHttpRespon getDeptList(IdmHttpRequest request) {
        String url = idmHttpProperties.getUrl() + GET_DEPT_LIST_URL;
        Map<String, String> headers = IdmHttpClient.getHeaders(idmHttpProperties);
        log.info("Get department  list   ..., request:{}", request);
        JsonNode jsonResult;
        try {
            jsonResult = IdmHttpClient.post(url, headers, request);
            log.info("Get department list success!");
            return JsonUtil.getObjectMapper().treeToValue(jsonResult, IdmHttpRespon.class);
        } catch (IdmHttpException | JsonProcessingException e) {
            log.error("Get department list failed, request:{},  error message:{}", request, e.getMessage(), e);
            throw new IdmHttpException("查询部门列表错误！", e);
        }
    }
}
